package com.thinklib.service.impl;

import com.thinklib.bean.RoleUnit;
import com.thinklib.bean.User;
import com.thinklib.mapper.UserMapper;
import com.thinklib.service.AuthService;
import com.thinklib.util.JsonData;
import com.thinklib.util.JwtUtils;
import com.thinklib.util.MD5Digest;
import com.thinklib.util.MailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@Service
public class AuthServiceImpl implements AuthService {

	@Resource
	UserMapper userMapper;

	@Value("${user.avatar.url}")
	private String userAvatarUrl;

	@Resource
	private User user;

	@Resource
	private AuthService authService;

	@Override
	public String findUserByUsername(String email, String password) {
		User user = userMapper.getUserByUsername(email);
		String pwd = MD5Digest.md5(password);
		if (user == null) {
			return null;
		}else if(user.getPassword().equals(pwd)){
			String token = JwtUtils.jwtEncryption(user);
			return token;
		}else {
			return null;
		}
	}

	@Override
	public int addUser(User user) {
		int affectLine = userMapper.addUser(user);
		return affectLine;
	}

	@Override
	public int activationEmail(String code) {
		int effectLine = userMapper.activationEmail(code);
		if (effectLine == 1) {
			return effectLine;
		}else {
			return 0;
		}
	}

	@Override
	public User findUserByCode(String code) {
		User user = userMapper.findUserByCode(code);
		return user;
	}

	@Override
	public List<User> findAllUser() {
		List<User> userList = (List<User>) userMapper.findAllUser();
		return userList;
	}

	@Override
	public RoleUnit findRoleByUsername(int userId) {
		RoleUnit roleUnit = userMapper.findRoleByUserId(userId);
		return roleUnit;
	}

	@Override
	public User findUserByEmail(String email) {
		return userMapper.findUserByEmail(email);
	}

	@Override
	public JsonData register(HttpServletRequest request, String email, String phone, String nickname, String password, int sex) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		MultipartFile avatar = multiRequest.getFile("avatar");

		String avatarName = avatar.getOriginalFilename();
		// 获取文件大小
		long size = avatar.getSize();
		// 获取文件名称
		String fileName = avatarName.substring(0, avatarName.lastIndexOf("."));
		// 获取文件后缀名
		String fileSuffix = avatarName.substring(avatarName.lastIndexOf("."));
		// 生成随机文件名和激活码
		UUID uuid = UUID.randomUUID();
		// 去掉UUID的横杠
		String newUuid = "think" + Long.toHexString(uuid.getMostSignificantBits())
				+ Long.toHexString(uuid.getLeastSignificantBits());
		// 获取当前时间
		long currentDate = System.currentTimeMillis();
		// 格式化当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String currentDateStr = sdf.format(currentDate);
		// 创建当前时间文件夹
		File currentDateFile = new File(userAvatarUrl + File.separator + currentDateStr);
		// 判断当前时间文件夹是否存在
		if (!currentDateFile.exists()) {
			currentDateFile.getParentFile().mkdirs();
		}

		// 拼接文件路径
		String fileUrl = currentDateFile + File.separator + newUuid + fileSuffix;

		File fileDest = new File(fileUrl);

		if (!fileDest.exists() || !fileDest.isDirectory()) {
			fileDest.getParentFile().mkdirs();
		}
		try {
			avatar.transferTo(fileDest);
		} catch (IOException e) {
			e.printStackTrace();
		}

		user.setEmail(email);
		user.setPhone(phone);
		user.setAvatar(File.separator + "user_avatar" + File.separator + currentDateStr + File.separator + newUuid + fileSuffix);
		user.setPassword(MD5Digest.md5(password));
		user.setNickname(nickname);
		user.setSex(sex);
		user.setState(0);
		user.setActivationCode(newUuid);
		// 添加用户
		int affectLine = authService.addUser(user);
		// 发送验证邮件
		new Thread(new MailUtil(email, newUuid)).start();
		return JsonData.buildSuccess("success");
	}


}
